<template>
	<view class="after-sale-container page-container">
		<!-- 顶部统计 -->
		<view class="stats-section">
			<view class="stat-item" @click="switchTab(0)">
				<text class="stat-number">{{ stats.total }}</text>
				<text class="stat-label">总申请</text>
			</view>
			<view class="stat-item" @click="switchTab(1)">
				<text class="stat-number">{{ stats.pending }}</text>
				<text class="stat-label">待审核</text>
			</view>
			<view class="stat-item" @click="switchTab(2)">
				<text class="stat-number">{{ stats.approved }}</text>
				<text class="stat-label">已同意</text>
			</view>
			<view class="stat-item" @click="switchTab(3)">
				<text class="stat-number">{{ stats.rejected }}</text>
				<text class="stat-label">已拒绝</text>
			</view>
			<view class="stat-item" @click="switchTab(4)">
				<text class="stat-number">{{ stats.completed }}</text>
				<text class="stat-label">已完成</text>
			</view>
		</view>

		<!-- 筛选标签 -->
		<view class="filter-tabs">
			<view class="filter-tab" :class="{ active: activeTab === index }" v-for="(tab, index) in statusTabs"
				:key="index" @click="switchTab(index)">
				<text class="tab-text">{{ tab.name }}</text>
			</view>
		</view>

		<!-- 售后列表 -->
		<view class="after-sale-list">
			<view class="after-sale-card" v-for="(item, index) in afterSaleList" :key="item.id"
				@click="toAfterSaleDetail(item)">
				<!-- 售后头部 -->
				<view class="after-sale-header">
					<view class="after-sale-info">
						<text class="after-sale-no">售后单号：{{ item.after_sale_sn }}</text>
						<text class="after-sale-date">申请时间：{{ item.apply_time }}</text>
					</view>
					<view class="after-sale-status" :class="'status-' + getStatusText(item.after_sale_status)">
						{{ item.after_sale_status_desc }}
					</view>
				</view>

				<!-- 订单信息 -->
				<view class="order-info">
					<text class="order-no">关联订单：S{{ item.order_id }}</text>
					<text class="after-sale-type">售后类型：{{ getTypeTitle(item.after_sale_type) }}</text>
				</view>

				<!-- 商品信息 -->
				<view v-for="skuitem in item.sku_info" :key="skuitem.id" class="product-info">
					<image :src="$tools.buildUrl(skuitem.main_image)" mode="aspectFill" class="product-image"></image>
					<view class="product-details">
						<text class="product-name">{{ skuitem.spu_name }}</text>
						<text class="product-spec">{{ skuitem.sku_name }}</text>
						<text class="product-price">¥{{ skuitem.actual_price }}</text>
					</view>
					<view class="product-quantity">
						<text class="quantity-text">x{{ skuitem.quantity }}</text>
					</view>
				</view>

				<!-- 申请原因 -->
				<view class="reason-section">
					<text class="reason-label">申请原因：</text>
					<text class="reason-text">{{ item.reason }}</text>
				</view>

				<!-- 操作按钮 -->
				<view class="action-buttons">
					<button class="action-btn approve-btn" v-if="item.after_sale_status === 0"
						@click.stop="approveAfterSale(item)">
						同意
					</button>
					<button class="action-btn reject-btn" v-if="item.after_sale_status === 0"
						@click.stop="rejectAfterSale(item)">
						拒绝
					</button>
					<button class="action-btn detail-btn" @click.stop="toAfterSaleDetail(item)">
						查看详情
					</button>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="afterSaleList.length === 0">
			<image src="@/static/images/empty-after-sale.png" mode="aspectFit" class="empty-image"></image>
			<text class="empty-text">{{ getEmptyText() }}</text>
		</view>

		<!-- 审核弹窗 -->
		<u-popup :show="showAuditPopup" @close="closeAuditPopup" mode="center" border-radius="20">
			<view class="audit-popup">
				<view class="popup-header">
					<text class="popup-title">{{ auditType === 'approve' ? '同意售后' : '拒绝售后' }}</text>
				</view>
				<view class="popup-content">
					<view class="form-item">
						<text class="form-label">审核备注</text>
						<textarea class="form-textarea"
							:placeholder="auditType === 'approve' ? '请输入同意原因（可选）' : '请输入拒绝原因'" v-model="auditRemark"
							maxlength="200"></textarea>
					</view>
				</view>
				<view class="popup-actions">
					<button class="cancel-btn" @click="closeAuditPopup">取消</button>
					<button class="confirm-btn" @click="confirmAudit">确认</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				activeTab: 0,
				showAuditPopup: false,
				auditType: '', // 'approve' 或 'reject'
				auditRemark: '',
				currentAfterSale: null,
				// 统计数据
				stats: {
					total: 0,
					pending: 0,
					approved: 0,
					rejected: 0,
					completed: 0
				},
				// 状态标签
				statusTabs: [{
						name: '全部',
						status: '0'
					},
					{
						name: '待审核',
						status: '1'
					},
					{
						name: '已同意',
						status: '2'
					},
					{
						name: '已拒绝',
						status: '3'
					},
					{
						name: '已完成',
						status: '4'
					}
				],
				searchKeyword: '',
				hasSearched: false,
				recordCount: 0,
				page: 1,
				limit: 10,
				afterSaleList: [] // 售后列表
			}
		},

		onLoad() {
			this.onSearch()
			this.loadDataState()
		},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {
			if (!this.hasSearched) {
				this.page = 1
				this.recordCount = 0
				this.afterSaleList = []
				this.loadDataList()
			}
		},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {
			// 下拉触底，先判断是否有请求正在进行中
			// 以及检查当前请求页数是不是小于数据总页数，如符合条件，则发送请求
			const page = this.page
			const limit = this.limit
			const recordCount = this.recordCount
			if (!this.hasSearched && page * limit < recordCount) {
				this.page++
				setTimeout(() => {
					this.loadDataList()
				}, 500)
			}
		},

		methods: {
			onSearch() {
				this.page = 1
				this.recordCount = 0
				this.afterSaleList = []
				this.loadDataList()
				this.loadDataState()
			},

			// 加载售后列表
			loadDataList() {
				if (this.hasSearched) {
					return false
				}
				this.hasSearched = true
				if (this.activeTab < 0) {
					this.activeTab = 0
				}
				const status = this.statusTabs[this.activeTab].status
				this.$api.agent.GetAfterSalesList({
					page: this.page,
					limit: this.limit,
					keyword: this.searchKeyword,
					status: status,
				}).then(res => {
					this.hasSearched = false
					this.recordCount = res.count
					res.data.forEach(item => {
						item.sku_info = this.$tools.parseJsonObject(item.sku_info);
						item.evidence = this.$tools.parseJsonObject(item.evidence);
					})
					this.afterSaleList = this.afterSaleList.concat(res.data)
				}).catch(err => {
					this.hasSearched = false
					if (this.page > 0) {
						this.page--
					}
				})
			},

			loadDataState() {
				this.$api.agent.GetAfterSalesTJ().then(res => {
					this.stats = res.data
				})
			},

			// 切换状态标签
			switchTab(index) {
				this.activeTab = index
				this.onSearch()
			},

			// 获取售后类型
			getTypeTitle(type) {
				const titleMap = {
					1: '退货',
					2: '换货',
					3: '仅退款',
					4: '补寄'
				}
				return titleMap[type] || '未知'
			},

			// 获取状态标识
			getStatusText(status) {
				const statusMap = {
					0: 'pending',
					1: 'approved',
					2: 'rejected',
					3: 'pending',
					4: 'pending',
					5: 'pending',
					6: 'pending',
					7: 'pending',
					8: 'pending',
					9: 'completed',
					10: 'completed',
					11: 'completed'
				}
				return statusMap[status] || 'pending'
			},

			// 获取空状态文字
			getEmptyText() {
				const textMap = {
					0: '暂无售后申请',
					1: '暂无待审核的售后',
					2: '暂无已同意的售后',
					3: '暂无已拒绝的售后',
					4: '暂无已完成的售后'
				}
				return textMap[this.activeTab] || '暂无售后申请'
			},

			// 同意售后
			approveAfterSale(item) {
				this.currentAfterSale = item
				this.auditType = 'approve'
				this.auditRemark = ''
				this.showAuditPopup = true
			},

			// 拒绝售后
			rejectAfterSale(item) {
				this.currentAfterSale = item
				this.auditType = 'reject'
				this.auditRemark = ''
				this.showAuditPopup = true
			},

			// 关闭审核弹窗
			closeAuditPopup() {
				this.showAuditPopup = false
				this.currentAfterSale = null
				this.auditRemark = ''
			},

			// 确认审核
			confirmAudit() {
				if (this.auditType === 'reject' && !this.auditRemark.trim()) {
					uni.showToast({
						title: '请输入拒绝原因',
						icon: 'none'
					})
					return
				}

				uni.showLoading({
					title: '处理中...'
				})

				this.$api.agent.AfterSalesCheck({
					id: this.currentAfterSale.id,
					check_status: this.auditType === 'reject' ? 2 : 1,
					chack_reason: this.auditRemark,
				}).then(res => {
					uni.hideLoading()

					// 更新售后状态
					this.setOrderStatus(res.data)

					// 更新统计数据
					this.loadDataState()
					this.closeAuditPopup()

					uni.showToast({
						title: this.auditType === 'approve' ? '已同意售后申请' : '已拒绝售后申请',
						icon: 'success'
					})
				})
			},

			setOrderStatus(afterSale) {
				const index = this.afterSaleList.findIndex(o => o.id === afterSale.id)
				if (index >= 0) {
					afterSale.sku_info = this.$tools.parseJsonObject(afterSale.sku_info);
					afterSale.evidence = this.$tools.parseJsonObject(afterSale.evidence);
					this.$set(this.afterSaleList, index, afterSale)
				}
			},

			// 跳转到售后详情
			toAfterSaleDetail(item) {
				uni.navigateTo({
					url: `/dealer-package/order/after-sale-detail?id=${item.id}`
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.after-sale-container {
		background-color: #f8f9fa;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}

	/* 统计区域 */
	.stats-section {
		display: flex;
		background-color: white;
		margin: 20rpx;
		border-radius: 16rpx;
		padding: 30rpx 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.stat-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 8rpx;
	}

	.stat-number {
		font-size: 32rpx;
		font-weight: bold;
		color: #52a58a;
	}

	.stat-label {
		font-size: 24rpx;
		color: #666;
	}

	/* 筛选标签 */
	.filter-tabs {
		display: flex;
		background-color: white;
		margin: 0 20rpx 20rpx;
		border-radius: 16rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.filter-tab {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 16rpx 8rpx;
		border-radius: 12rpx;
		position: relative;
		transition: all 0.3s ease;
	}

	.filter-tab.active {
		background-color: #52a58a;
	}

	.tab-text {
		font-size: 28rpx;
		color: #666;
		transition: color 0.3s ease;
	}

	.filter-tab.active .tab-text {
		color: white;
		font-weight: bold;
	}

	.tab-badge {
		position: absolute;
		top: 8rpx;
		right: 8rpx;
		background-color: #ff4757;
		border-radius: 20rpx;
		min-width: 32rpx;
		height: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.badge-text {
		font-size: 20rpx;
		color: white;
		font-weight: bold;
	}

	/* 售后列表 */
	.after-sale-list {
		padding: 0 20rpx;
	}

	.after-sale-card {
		background-color: white;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	/* 售后头部 */
	.after-sale-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 20rpx;
	}

	.after-sale-info {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.after-sale-no {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}

	.after-sale-date {
		font-size: 24rpx;
		color: #999;
	}

	.after-sale-status {
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		font-weight: bold;
	}

	.status-pending {
		background-color: #fff3cd;
		color: #856404;
	}

	.status-approved {
		background-color: #d4edda;
		color: #155724;
	}

	.status-rejected {
		background-color: #f8d7da;
		color: #721c24;
	}

	.status-completed {
		background-color: #cce5ff;
		color: #004085;
	}

	/* 订单信息 */
	.order-info {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
		margin-bottom: 20rpx;
		padding: 20rpx;
		background-color: #f8f9fa;
		border-radius: 12rpx;
	}

	.order-no,
	.after-sale-type {
		font-size: 26rpx;
		color: #666;
	}

	/* 商品信息 */
	.product-info {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-bottom: 20rpx;
	}

	.product-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
	}

	.product-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.product-name {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}

	.product-spec {
		font-size: 24rpx;
		color: #999;
	}

	.product-price {
		font-size: 28rpx;
		color: #52a58a;
		font-weight: bold;
	}

	.product-quantity {
		display: flex;
		align-items: center;
	}

	.quantity-text {
		font-size: 26rpx;
		color: #666;
	}

	/* 申请原因 */
	.reason-section {
		margin-bottom: 30rpx;
		padding: 20rpx;
		background-color: #f8f9fa;
		border-radius: 12rpx;
	}

	.reason-label {
		font-size: 26rpx;
		color: #666;
		margin-right: 10rpx;
	}

	.reason-text {
		font-size: 26rpx;
		color: #333;
	}

	/* 操作按钮 */
	.action-buttons {
		display: flex;
		gap: 20rpx;
		justify-content: flex-end;
	}

	.action-btn {
		padding: 0rpx 32rpx;
		border-radius: 25rpx;
		font-size: 26rpx;
		border: none;
	}

	.approve-btn {
		background-color: #52a58a;
		color: white;
	}

	.reject-btn {
		background-color: #ff4757;
		color: white;
	}

	.detail-btn {
		background-color: #f8f9fa;
		color: #666;
		border: 2rpx solid #e9ecef;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 40rpx;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}

	/* 审核弹窗 */
	.audit-popup {
		width: 600rpx;
		background-color: white;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.popup-header {
		padding: 40rpx 30rpx 20rpx;
		text-align: center;
		border-bottom: 2rpx solid #f0f0f0;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.popup-content {
		padding: 30rpx;
	}

	.form-item {
		margin-bottom: 30rpx;
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
	}

	.form-textarea {
		width: 100%;
		min-height: 200rpx;
		padding: 20rpx;
		border: 2rpx solid #e9ecef;
		border-radius: 12rpx;
		font-size: 26rpx;
		color: #333;
		background-color: #f8f9fa;
	}

	.popup-actions {
		display: flex;
		border-top: 2rpx solid #f0f0f0;
	}

	.cancel-btn,
	.confirm-btn {
		flex: 1;
		padding: 30rpx;
		font-size: 28rpx;
		border: none;
		background-color: transparent;
	}

	.cancel-btn {
		color: #999;
	}

	.confirm-btn {
		color: #52a58a;
		font-weight: bold;
		border-left: 2rpx solid #f0f0f0;
	}
</style>